package com.lyl.springcloud.controller;

import com.lyl.springcloud.model.Payment;
import com.lyl.springcloud.model.Result;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.stream.events.Comment;

/**
 * @author lylbell
 * @date 2021-05-25 17:11
 */
@RestController
public class OrderController {
//    public static final String PAYMENT_URL = "http://localhost:8081";//单机版
    public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";//集群版。需要开启负载均衡，不然不知道对应哪个服务

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public Result<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create",payment,Result.class);
    }


    //getForObject返回的对象为响应体中数据转化的对象，基本上可以理解为JSON
    @GetMapping("/consumer/payment/getById/{id}")
    public Result<Payment> getById(@PathVariable("id")Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/getById/" + id, Result.class);
    }

    //getForEntity返回对象为ResponseEntity对象，包含了响应的一些重要信息，比如响应头，响应状态码，响应体等
    @GetMapping("/consumer/payment/getByEntity/{id}")
    public Result<Payment> getPayment(@PathVariable("id") Long id) {
        ResponseEntity<Result> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/getById/"+id, Result.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        }else {
            return new Result<>(444,"查询失败");
        }
    }

    @GetMapping("/consumer/payment/zipkin")
    public String orderZipkin() {
        return restTemplate.getForObject(PAYMENT_URL+"/payment/zipkin",String.class);
    }
}
